/*
Copyright 2005-2014 CP Fricano - All Rights Reserved

This software and source code is licensed under the Apache
License, Version 2.0. You may not use this software or source
code except in compliance with the License.  You may obtain a
copy of the License at: http://www.apache.org/licenses/LICENSE-2.0.
Use and distributed under this License is on an "as is" basis,
without expressed or implied warranties or conditions of any kind.
See the License for the specific language governing permissions and
limitations.
 */

package com.fricano.java42.instructional.example.time;

public class J42Time {

    public static double getResolution_ClockMS() {
        double resolution = 0.0d;
        final int maxLoops = 100;
        double iterationsAvg = 0;
        double millisecAvg = 0;
        for (int x = 0; x != maxLoops; x++) {
            {
                final long startMS = System.currentTimeMillis();
                long nowMS = System.currentTimeMillis();
                long iterations = 0;
                while ((nowMS = System.currentTimeMillis()) == startMS) {
                    iterations++;
                }
                iterationsAvg += iterations;
                millisecAvg += (nowMS - startMS);
            }
        }
        resolution = millisecAvg / maxLoops;
        // final double avgI = iterationsAvg / maxLoops;
        // System.out.println("   NS/interation  =" + ((millisecAvg * 1000000) / avgI) / maxLoops);
        // System.out.println("Avegage iterations=" + avgI);
        // System.out.println("System.currentTimeMillis() resolution is " + resolution + " milliseconds");
        return resolution;
    }

    public static double getResolution_TimerNS() {
        double resolution = 0.0d;
        final int maxLoops = 1000000;
        double iterationsAvg = 0;
        double nanosecAvg = 0;
        for (int x = 0; x != maxLoops; x++) {
            {
                final long startNS = System.nanoTime();
                long nowNS = System.nanoTime();
                long iterations = 0;
                while ((nowNS = System.nanoTime()) == startNS) {
                    iterations++;
                }
                iterationsAvg += iterations;
                nanosecAvg += (nowNS - startNS);
            }
        }
        resolution = nanosecAvg / maxLoops;
        final double avgI = iterationsAvg / maxLoops;
        // System.out.println("   NS/interation  =" + ((nanosecAvg) / avgI) / maxLoops);
        // System.out.println("Avegage iterations=" + avgI);
        // System.out.println("System.nanoTime() resolution is " + resolution + " nanoseconds");
        return resolution;
    }

}
